package com.uchiha.nova.mainService.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.uchiha.nova.core.model.dto.NovaOauthTokenDTO;
import com.uchiha.nova.core.model.entity.OauthClientDetails;
import com.uchiha.nova.core.model.entity.UserEntity;
import com.uchiha.nova.core.model.entity.WechaterEntity;
import com.uchiha.nova.core.tool.api.R;
import com.uchiha.nova.core.tool.constant.RedisCacheConstants;
import com.uchiha.nova.core.tool.support.AuthToken;
import com.uchiha.nova.core.tool.support.NovaUser;
import com.uchiha.nova.core.tool.util.AuthUtil;
import com.uchiha.nova.mainService.mapper.WechaterMapper;
import com.uchiha.nova.mainService.service.OauthTokenService;
import com.uchiha.nova.mainService.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 周林静
 * @Date 2025-07-21 9:56
 * @Version 1.0
 */
@Service("wx_code")
@Slf4j
public class WxLoginImpl implements OauthTokenService {
    @Resource
    UserService userService;
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    WechaterMapper wechaterMapper;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Value("${wechat.APPID}")
    private String appId;
    @Value("${wechat.APPSECRET}")
    private String appSecret;
    @Value("${nova.oauth.token-key}")
    String tokenKey;

    @Override
    public R getToken(NovaOauthTokenDTO dto) {
        String code = dto.getCode();
        String authorizeUrl= MessageFormat.format(
                "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid={0}&secret={1}&js_code={2}",
                appId, appSecret, code);
        RestTemplate restTemplate=new RestTemplate();
        String res=restTemplate.getForObject(authorizeUrl,String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);
        log.info("腾讯的返回:{}",jsonObject);
        String openid=jsonObject.getString("openid");
        log.info("openid腾讯:{}",openid);
        if(ObjectUtil.isEmpty(openid)){
            return R.fail("无效的code");
        }else{
            WechaterEntity wechater = wechaterMapper.selectOne(new QueryWrapper<WechaterEntity>().eq("open_id",openid));
            if (ObjectUtil.isEmpty(wechater)) {
                Map<String,Object> map = new HashMap<>();
                map.put("openid",openid);
               return R.data(601,map,"请注册");
            }else{
                OauthClientDetails clientDetails = (OauthClientDetails) redisTemplate.opsForValue().get(RedisCacheConstants.NOVA_OAUTH_CLIENT+dto.getClientId());
                UserEntity userEntity = userService.getById(wechater.getUserId());
                NovaUser user = userService.getNovaUser(userEntity);
                AuthToken authToken = AuthUtil.getToken(user,tokenKey, (long) (1000*clientDetails.getAccessTokenValidity()), (long) (1000*clientDetails.getRefreshTokenValidity()));
                authToken.setUserId(userEntity.getId());
                return R.data(authToken);
            }

        }
    }
}
